$(function () {//  加载完执行
    // 默认聊天列表(0)  or  联系人列表(1)
    $("#iconSet > div").eq(0).click();
    // 默认滚动条最底部
    $(".chatWindow-content-ul").scrollTop($(".chatWindow-content-ul")[0].scrollHeight);
    // 默认自动获取焦点
    $("#weChatNews").focus();
    // 获取联系人列表
    websocketWx();
});

function websocketWx() {
    var websocket = null;
    var id = document.getElementById("id").value;
    if ('WebSocket' in window) {
        websocket = new WebSocket("ws://www.yiyatest.cn/WebSocketWxChat/" + id)
    } else {
        alert('Not support websocket！该浏览器不支持实时刷新，请使用谷歌浏览器急速模式！')
    }
    websocket.onerror = function () {
        setMessageInnerHTML("error")
    };
    websocket.onopen = function (event) {
        setMessageInnerHTML("open")
    };
    websocket.onmessage = function (event) {
        setMessageInnerHTML(event.data)
    };
    websocket.onclose = function () {
        setMessageInnerHTML("close")
    };
    window.onbeforeunload = function () {
        websocket.close()
    };

    function setMessageInnerHTML(innerHTML) {
        queryChatRecordBySender()
    }

    function closeWebSocket() {
        websocket.close()
    }

    function send() {
        var message = document.getElementById('text').value;
        websocket.send(message)
    }
}

// -------------  请求数据  -------------
// 获取联系人列表
function querySenderList() {
    $.ajax({
        url: Feng.ctxPath + "/guestDimension/querySenderList",
        type: "GET",
        dataType: "json",
        success: function (data) {
            var friendsListContent = '';
            for (var i = 0; i < data.length; i++) {
                friendsListContent +=
                    '<div class="friendsList-li-content">' ;
                if(data[i].headimgurl==""||data[i].headimgurl==null){
                    friendsListContent +=
                        '<div class="friendsList-li-head"><img src="https://pynnn.oss-cn-hangzhou.aliyuncs.com/one/yiyatouxiang.png" alt=""></div>' ;
                }else {
                    friendsListContent +=
                        '<div class="friendsList-li-head"><img src="' + data[i].headimgurl + '" alt=""></div>' ;
                }
                friendsListContent +='<div class="friendsList-li-text">' +
                    '<div class="friendsList-li-name">' + data[i].name + '(未读' + data[i].isNewCount + ')</div>' +
                    '<div class="friendsList-li-openId" value="' + data[i].openId + '"></div>' +
                    '<div class="friendsList-li-openId" value="' + data[i].phone + '"></div>' +
                    '</div>' +
                    '</div>'
            }
            $("#friendsList-ul").html('<li class="friendsList-li"><div class="friendsList-li-title">A</div>' + friendsListContent + '</li>');
        }
    });
}

// 获取联系人列表
function queryChatRecordBySender() {
    if (!$(this).hasClass('friendsList-active')) {
        // 改变样式
        $(this).parents('.friendsList-ul').find('.friendsList-li-content').removeClass('friendsList-active');
        $(this).addClass('friendsList-active');
        // 获取聊天记录
        var openId = document.getElementById("openId").value;
        $.ajax({
            url: Feng.ctxPath + "/guestDimension/queryChatRecordBySender",
            type: "POST",
            dataType: "json",
            data: {'sender': openId},
            success: function (data) {
                var chatWindowContent = '';
                for (var i = 0; i < data.length; i++) {
                    if (data[i].sendStatus === 1) {
                        if(data[0].headimgurl==""||data[i].headimgurl==null){
                            chatWindowContent +=
                                '<li class="chatWindow-content-li content-li-left"><img src="https://pynnn.oss-cn-hangzhou.aliyuncs.com/one/yiyatouxiang.png" alt=""><span>' + data[i].sendTime + '</span><div><span>' + data[i].chatRecord + '</span></div></li>'
                        }else {
                            chatWindowContent +=
                                '<li class="chatWindow-content-li content-li-left"><img src="' + data[0].headimgurl + '" alt=""><span>' + data[i].sendTime + '</span><div><span>' + data[i].chatRecord + '</span></div></li>'
                        }
                    } else if (data[i].sendStatus === 2) {
                        chatWindowContent +=
                            '<li class="chatWindow-content-li content-li-right"><img src="https://pynnn.oss-cn-hangzhou.aliyuncs.com/one/yiyatouxiang.png" alt=""><span>' + data[i].sendTime + '</span><div><span>' + data[i].chatRecord + '</span></div></li>'
                    }
                }
                $("#chatWindow-content-ul").html(chatWindowContent).scrollTop($("#chatWindow-content-ul").scrollHeight);
                $("#chatWindow-content-ul").scrollTop($(".chatWindow-content-ul")[0].scrollHeight);
                querySenderList();
            }
        });
    }
}

// 好友列表搜索刷新
function screenFriends() {
    var friendsInput = $("#friendsInput").val();
    $.ajax({
        url: Feng.ctxPath + "/guestDimension/fuzzyQueryBySender",
        type: "POST",
        dataType: "json",
        data: {'sender': friendsInput},
        success: function (data) {
            querySenderList();
        }
    });
}

// -------------  JQ操作  -------------
//  聊天 or 好友列表切换
$("#iconSet > div").click(function () {
    if (!$(this).hasClass('selection')) {
        $(this).addClass('selection').siblings().removeClass('selection');
        $(".middleList").hide().eq($(this).index()).show();
        $("#iconSet > div").find('img').toggle();
    }
});
// 点击 li 添加样式
$("#chatList").on('click', '.chatList-li', function () {
    $(this).addClass('chatList-active').siblings().removeClass('chatList-active');
});
$("#friendsList").on('click', '.friendsList-li-content', function () {
    if (!$(this).hasClass('friendsList-active')) {
        // 改变样式
        $(this).parents('.friendsList-ul').find('.friendsList-li-content').removeClass('friendsList-active');
        $(this).addClass('friendsList-active');
        // 获取聊天记录
        var openId = $(this).find('.friendsList-li-openId').attr('value');
        var name = $(this).find('.friendsList-li-name').html();
        var simplename = "";
        $.ajax({
            url: Feng.ctxPath + "/guestDimension/queryChatRecordBySender",
            type: "POST",
            dataType: "json",
            data: {'sender': openId},
            success: function (data) {
                var chatWindowContent = '';
                for (var i = 0; i < data.length; i++) {
                    simplename = '<div class="friendsList-li-simplename">' + data[0].simplename + '</div>';
                    if (data[i].sendStatus === 1) {
                        if(data[0].headimgurl==""||data[i].headimgurl==null){
                            chatWindowContent +=
                                '<li class="chatWindow-content-li content-li-left"><img src="https://pynnn.oss-cn-hangzhou.aliyuncs.com/one/yiyatouxiang.png" alt=""><span>' + data[i].sendTime + '</span><div><span>' + data[i].chatRecord + '</span></div></li>'
                        }else {
                            chatWindowContent +=
                                '<li class="chatWindow-content-li content-li-left"><img src="' + data[0].headimgurl + '" alt=""><span>' + data[i].sendTime + '</span><div><span>' + data[i].chatRecord + '</span></div></li>'
                        }
                    } else if (data[i].sendStatus === 2) {
                        chatWindowContent +=
                            '<li class="chatWindow-content-li content-li-right"><img src="https://pynnn.oss-cn-hangzhou.aliyuncs.com/one/yiyatouxiang.png" alt=""><span>' + data[i].sendTime + '</span><div><span>' + data[i].chatRecord + '</span></div></li>'
                    }
                }
                document.getElementById("reservationsId").value = data[0].reservationsId;
                document.getElementById("openId").value = openId;
                $("#chatWindow-top-title").html(data[0].name+"("+data[0].simplename+")").attr('value', openId);
                $("#chatWindow-content-ul").html(chatWindowContent).scrollTop($("#chatWindow-content-ul").scrollHeight);
                $("#chatWindow-content-ul").scrollTop($(".chatWindow-content-ul")[0].scrollHeight);
                querySenderList();
            }
        });
    }
});

$("#chatWindow-top-title").click(function () {
    var reservationsId = document.getElementById("reservationsId").value;
    if (reservationsId.length == 0 || reservationsId == null || reservationsId == "") {
        var index = parent.layer.open({
            type: 2,
            title: '到店客户详情',
            area: ['100%', '100%'],
            fix: true,
            maxmin: true,
            content: Feng.ctxPath + '/guest/doNoClose'
        });
        this.layerIndex = index;
    } else {
        var index = parent.layer.open({
            type: 2,
            title: '到店客户详情',
            area: ['100%', '100%'],
            fix: true,
            maxmin: true,
            content: Feng.ctxPath + '/customerDetails/to_openByReservationKwId/' + reservationsId + "/0"
        });
        this.layerIndex = index;
    }
});

// 输入框获取焦点背景变白
$("#weChatNews").focus(function () {
    $('.chatWindow-operation,#weChatNews').css('background', '#FFFFFF');
});
$("#weChatNews").blur(function () {
    $('.chatWindow-operation,#weChatNews').css('background', '');
});
// 鼠标移入列表出现滚动条
$(".chatList-ul").hover(function () {
    $(".chatList-ul").css("overflow", "auto")
}, function () {
    $(".chatList-ul").css("overflow", "hidden")
});
$(".friendsList-ul").hover(function () {
    $(".friendsList-ul").css("overflow", "auto")
}, function () {
    $(".friendsList-ul").css("overflow", "hidden")
});

// 消息发送
function messageSending() {
    var weChatNews = $("#weChatNews").val();
    if (weChatNews === "" || weChatNews === undefined) {
        alert('不能发送空消息');
        return false;
    } else {
        $(".chatWindow-content-ul").append('<li class="chatWindow-content-li content-li-right"><img src="' + Feng.ctxPath + '/static/customer/headPortrait.jpg" alt=""><span>' + weChatNews + '</span></li>');
        $("#weChatNews").val("");
        $(".chatWindow-content-ul").scrollTop($(".chatWindow-content-ul")[0].scrollHeight);
        $('.chatWindow-operation,#weChatNews').css('background', '#FFFFFF');
        // 发送消息给服务器
        var openId = $('#chatWindow-top-title').attr('value');
        $.ajax({
            url: Feng.ctxPath + "/guestDimension/guestSenderChatRecord",
            type: "POST",
            dataType: "json",
            data: {"openId": openId, "weChatNews": weChatNews},
            success: function (data) {
            }
        });
    }
}

// 回车事件
$("#weChatNews").keydown(function (e) {    // 按键按下时触发的事件；
    var et = e || window.event;
    var keycode = et.charCode || et.keyCode;
    if (keycode == 13) {
        if (window.event) {
            window.event.returnValue = false;
            messageSending();
        } else {
            e.preventDefault(); //for firefox
        }
    }
});

// 点击发送按钮
$("#weChatBtn").click(function () {
    messageSending();
});